<script setup>
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import { getUserApi } from '@/api/users'

const router = useRouter()

const username = ref('')
const password = ref('')

const handlelogin = async () => {
  //获取后台所有用户
  const arr = await getUserApi()

  //判断
  for (let i = 0; i < arr.length; i++) {
    if (
      arr[i].username == username.value &&
      arr[i].password == password.value
    ) {
      localStorage.setItem('isLogin', true)
      router.push('/home')
    } else {
      if (arr[arr.length - 1] == arr[i]) {
        alert('您输入的用户名或密码有误，请重新输入！')
      } else {
        continue
      }
    }
  }
}
</script>

<template>
  <main>
    <div class="login">
      <h2>登录界面</h2>
      <div>
        <span>用户名：</span><input type="text" v-model.trim="username" />
      </div>
      <div>
        <span>&nbsp;&nbsp;&nbsp;密码：</span>
        <input type="password" v-model.trim="password" />
      </div>
      <button @click="handlelogin">登录</button>
    </div>
  </main>
</template>

<style scoped>
main {
  height: 100vh;
  background-image: url(../components/images/R-C.jpg);
  background-repeat: no-repeat;
  background-size: cover;
  background-position: center;
  background-attachment: fixed;
}
.login {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  gap: 20px;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 400px;
  height: 250px;
  border-radius: 5px;
  background: rgba(255, 255, 255, 0.7);
}

.login input {
  padding: 5px;
  border: 1px solid black;
  border-radius: 3px;
}

button {
  padding: 8px 20px;
  color: white;
  background: #00aaff;
  border: none;
  border-radius: 5px;
}

button:hover {
  background: #ff7a08;
}
</style>
